<script setup>
import { ref, markRaw, provide, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import ApiUrlSection from './components/ApiUrlSection.vue'
import {config} from './config'
import { message } from 'ant-design-vue'
// import {SwaggerUtils} from './swaggerUtils'

const router = useRouter()
const route = useRoute()

// 控制侧边栏显示/隐藏
const sidebarVisible = ref(true)

// 获取URL参数
const urlParams = new URLSearchParams(window.location.search)
const isAdmin = urlParams.has('admin') && urlParams.get('admin') === '1'

// 页面列表
const pages = [
  { id: 'Home', name: '首页', icon: '🏠', path: '/' },
  { id: 'ParameterConfig', name: 'PMS资源配置', icon: '🔧', path: '/parameter' },
  { id: 'CodeGenerationManagement', name: '代码生成管理', icon: '💻', path: '/code-generation-management' },
  { id: 'CodeStepGenerator', name: '需求文档生成代码', icon: '📝', path: '/code-step-generator' },
  // { id: 'RequirementAnalysis', name: '需求文档解析', icon: '📄', path: '/requirement-analysis' },
  // { id: 'TemplateManagement', name: '代码模板查看', icon: '📄', path: '/template-management' },
  { id: 'DataDictionary', name: '数据字典', icon: '📋', path: '/data-dictionary' },
  ...(isAdmin ? [
    { id: 'LogViewer', name: '操作日志查看2222', icon: '📋', path: '/log-viewer' },
  ] : [])
]

// 全局API状态
const apiState = reactive({
  url: '',
  data: null,
  loading: false
})

// 提供全局API状态给所有子组件
provide('apiState', apiState)

// 导航到指定路径
function navigateTo(path) {
  router.push(path)
}

// 切换侧边栏显示/隐藏
function toggleSidebar() {
  sidebarVisible.value = !sidebarVisible.value
}

// 加载API文档
async function loadApiDocs(url) {
  apiState.loading = true
  try {
    // 使用代理解决 CORS 问题
    const proxyUrl = `${config.domain}/api/proxy?url=${encodeURIComponent(url)}`
    const response = await fetch(proxyUrl)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.error || `HTTP error! status: ${response.status}`)
    }
    
    const contentType = response.headers.get('content-type')
    if (!contentType || !contentType.includes('application/json')) {
      const textResponse = await response.text()
      console.error('Non-JSON response:', textResponse.substring(0, 200))
      throw new Error('响应不是有效的JSON格式，请检查API地址是否正确')
    }
    
    const data = await response.json()
    apiState.data = data
    apiState.url = url
    
    // 检查是否为 OpenAPI 3.0.1
    if (!data.openapi || !data.openapi.startsWith('3.')) {
      return  message.error('该文档不是 OpenAPI 3.0.1 格式')
    }
    
    console.log('API文档加载成功')
  } catch (error) {
    if (error instanceof SyntaxError) {
      console.error('JSON解析错误:', error)
      message.error(`加载API文档失败: 响应数据不是有效的JSON格式，请检查API地址是否正确`)
    } else {
      console.error('加载API文档失败:', error)
      message.error(`加载API文档失败: ${error.message}`)
    }
  } finally {
    apiState.loading = false
  }
}

// 页面挂载时尝试自动加载缓存的API URL
onMounted(() => {
  const cachedUrl = localStorage.getItem('swaggerApiUrl');
  if (cachedUrl) {
    // 先设置URL，再自动加载
    apiState.url = cachedUrl;
    loadApiDocs(cachedUrl);
  }
})

// 控制哪些组件不要缓存
const excludedComponents = ref([])

// 监听路由变化，决定是否排除缓存
watch(
  () => route,
  (newRoute) => {
    // 只有在CustomCodeGeneration页面且没有id参数时才排除缓存
    if (newRoute.name === 'CustomCodeGeneration' && !newRoute.query.id) {
      // 添加到排除列表
      if (!excludedComponents.value.includes('CustomCodeGeneration')) {
        excludedComponents.value.push('CustomCodeGeneration')
      }
    } else {
      // 其他情况确保在排除列表中移除
      const index = excludedComponents.value.indexOf('CustomCodeGeneration')
      if (index > -1) {
        excludedComponents.value.splice(index, 1)
      }
    }
  },
  { immediate: true, deep: true }
)

</script>

<template>
  <div class="app-container">
    <div class="container">
      <!-- 顶部API URL输入框 -->
      <ApiUrlSection 
        v-model="apiState.url" 
        @load="loadApiDocs"
      />

      <div  class="app-content">

      <!-- 全局loading遮罩 -->
      <div v-show="apiState.loading" class="loading-overlay">
        <div class="loading-spinner">
          <div class="spinner-icon"></div>
          <p>正在加载API文档...</p>
        </div>
      </div>

      <!-- 侧边栏 -->
      <div v-show="sidebarVisible" class="sidebar">
        <h2>Swagger-Helper</h2>
        <ul class="menu">
          <li 
            v-for="page in pages" 
            :key="page.id"
            :class="['menu-item', { active: route.name === page.id }]"
            @click="navigateTo(page.path)"
          >
            <span class="icon">{{ page.icon }}</span>
            <span class="text">{{ page.name }}</span>
          </li>
        </ul>
      </div>
      
      <!-- 主内容区 -->
      <div class="main-content">
        <div class="toggle-sidebar-btn" @click="toggleSidebar">
          {{ sidebarVisible ? '◀' : '▶' }}
        </div>
        <!-- 使用router-view替代之前的条件渲染 -->
        <div class="page-content">
          <router-view v-slot="{ Component, route }">
            <keep-alive :exclude="excludedComponents">
              <component :is="Component" :key="route.fullPath" />
            </keep-alive>
          </router-view>
        </div>
      </div>

      </div>
      

    </div>
  </div>
</template>

<style scoped>
@import 'ant-design-vue/dist/reset.css';

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-track {
  background: rgba(230, 242, 255, 0.5);
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #66b2ff, #3399ff);
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #3399ff, #0080ff);
}

::-webkit-scrollbar-corner {
  background: rgba(230, 242, 255, 0.5);
}

.app-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
  color: #333;
  background: linear-gradient(135deg, #cce5ff 0%, #e6f2ff 100%);
  min-height: 100vh;
  font-size: 15px;
}

.container {
  display: flex;
  height: 100vh;
  max-width: 100%;
  margin: 0;
  background-color: #fff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  flex-direction: column;
}

.sidebar {
  width: 240px;
  background: linear-gradient(135deg, #e6f2ff 0%, #cce5ff 100%);
  padding: 15px 0;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  font-size: 16px;
  flex-direction: column;
}

.toggle-sidebar-btn {
  position: absolute;
  left: 240px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 60px;
  background: linear-gradient(135deg, #e6f2ff 0%, #cce5ff 100%);
  border: 1px solid #cce5ff;
  border-left: none;
  border-radius: 0 4px 4px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  z-index: 999;
  transition: all 0.3s ease;
}

.toggle-sidebar-btn:hover {
  background: linear-gradient(135deg, #cce5ff 0%, #99ccff 100%);
}

.sidebar:not(.sidebar-visible) + .main-content .toggle-sidebar-btn {
  left: 0;
}

.sidebar h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  padding: 0 15px;
}

.menu {
  list-style: none;
  padding: 0;
  margin: 0;
  flex: 1;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  color: #2c3e50;
  font-weight: 500;
  display: flex;
  align-items: center;
  font-size: 15px;
}

.menu-item:hover {
  background-color: rgba(102, 178, 255, 0.2);
}

.menu-item.active {
  background-color: rgba(102, 178, 255, 0.3);
  border-left: 3px solid #3399ff;
  color: #3399ff;
  font-weight: 600;
}

.icon {
  margin-right: 10px;
  font-size: 17px;
}

.app-content{
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.page-content {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.page-content h1 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
}

/* Loading遮罩样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
  font-size: 16px;
}

.spinner-icon {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

</style>
